package com.token.iot.bratterycharging.gateway;

import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import com.outstanding.framework.core.TransactionContext;
import com.token.iot.bratterycharging.gateway.api.Constant;

public class IDGeneration {

	// 静态变量存储最大值
	private static final AtomicInteger atomicNum = new AtomicInteger();
	private static final String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

	static public String createSeesionID() {
		// 线程安全的原子操作，所以此方法无需同步
		int newNum = atomicNum.incrementAndGet();
		int num = newNum % 100000;
		// 数字长度为5位，长度不够数字前面补0
		StringBuffer newStrNum = new StringBuffer(String.format("%05d", num));
		newStrNum = newStrNum.insert(0, chars.charAt((int) (Math.random() * 62)));
		TransactionContext.putData(Constant.SESSIONID, newStrNum.toString());
		return newStrNum.toString();
	}

	static public String createSeesionID(String defaultValue) {
		if (StringUtils.isBlank(defaultValue)) {
			
			
			return createSeesionID();
		} else {
			TransactionContext.putData(Constant.SESSIONID, defaultValue);
			return defaultValue;
		}
	}

	static public String getSessionID(byte[] b) {
		byte[] sessions = new byte[6];
		System.arraycopy(b, 5, sessions, 0, 6);
		String sessionid = new String(sessions);
		TransactionContext.putData(Constant.SESSIONID, sessionid);
		return sessionid;

	}

	static public void main(String[] args) throws Exception {
		IDGeneration generation = new IDGeneration();
		for (int i = 0; i < 100006; i++) {
			System.out.println(generation.createSeesionID());
		}
	}

}
